<template>
  <div class="chanxian-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" style="background-color: #ff4d4f; border-color: #ff4d4f;">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      ref="multipleTableRef"
      :data="tableData" 
      style="width: 100%" 
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" :index="getIndex" />
      <el-table-column prop="productionlinenumber" label="产线编码" width="120">
      </el-table-column>
      <el-table-column prop="workshopname" label="所属车间" width="150" />
      <el-table-column prop="descriptionofproductionline" label="产线描述" />
      <el-table-column prop="createName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          {{ scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD') : '' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)" style="color: #ff4d4f;">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <div style="margin-right: auto; line-height: 40px;">
        共 {{ pagination.total }} 条数据
      </div>
      <el-pagination
        v-model:current-page="pagination.pageindex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="prev, pager, next, jumper, sizes"
        :total="pagination.total"
        style="margin-left: auto;"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="产线编码" prop="productionLineCode" >
          <el-input v-model="formData.productionlinenumber" placeholder="请输入产线编码" />
        </el-form-item>
        <el-form-item label="产线名称" prop="productionLineName" >
          <el-input v-model="formData.nameofproductionline" placeholder="请输入产线名称" />
        </el-form-item>
        <el-form-item label="所属车间" prop="workshopCode" >
          <el-select v-model="formData.workid" placeholder="请选择车间">
            <el-option v-for="d in workshopList" :label="d.workshopname" :value="d.workid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产线描述" prop="descriptionOfProductionLine">
          <el-input v-model="formData.descriptionofproductionline" placeholder="请输入产线描述" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { APIs } from '../../Http/http';
import { ElMessage, ElMessageBox } from 'element-plus';
import  moment from 'moment'
// 表格数据
const tableData = ref<any[]>([]);
const multipleTableRef = ref<any>();
const selectedRows = ref<any[]>([]);

const columnSearch = reactive({
  productionLineCode: '',
  productionLineName: ''
});

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pageSize: 10,
  total: 0
});

// 弹窗数据
const dialogVisible = ref(false);
const dialogTitle = ref('添加产线');
const formRef = ref<any>();
const isEdit = ref(false);

// 车间列表
const workshopList = ref<any[]>([]);

// 表单数据
const formData = reactive({
  "productionlinenumber": "",
  "nameofproductionline": "",
  "workid": null,
  "descriptionofproductionline": ""
});

// 获取序号
const getIndex = (index: number) => {
  return (pagination.pageindex - 1) * pagination.pageSize + index + 1;
};

// 监听分页变化
watch(pagination, () => {
  getProductionLineList();
});

// 获取车间列表
const getWorkshopList = () => {
  APIs.get('/api/Read/ShowCheJian').then(res => {
    if (res.data.code === 100) {
      workshopList.value = res.data.data;
    }
  });
};

// 获取产线列表
const getProductionLineList = () => {
  APIs.get('/api/Read/GetProductionLineList', {
    params: {
      Pageindex: pagination.pageindex,
      PageSize: pagination.pageSize,
    }
  }).then(res => {
    if (res.data.code === 100) {
      tableData.value = res.data.data.data;
      pagination.total = res.data.data.totalCount;
    }
  })
};



// 添加产线
const handleAdd = () => {
  dialogTitle.value = '添加产线';
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑产线
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑产线';
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除产线
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条产线吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.post("/api/Write/DeleChanXian", row).then(res => {
      if (res.data.code == 100) {
        ElMessage.success("删除成功");
        getProductionLineList();
      }
    })
  });
};
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.productionlinePK,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  console.log(selectedRows.value)
  const requestData = {
    productionlinePKs: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个车间吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/PLDeleChanXian", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
       getWorkshopList()
      }
    })
  });
};


// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const apiPath = isEdit.value ? '/api/Write/UpdateChanXian' : '/api/Write/AddChanXian';
      APIs.post(apiPath, formData).then(res => {
        if (res.data.code === 100) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          getProductionLineList();
        }
      })
    }
  });
};

// 重置表单
const resetForm = () => {
  formData.productionlinenumber = '';
  formData.nameofproductionline = '';
  formData.workid = null;
  formData.descriptionofproductionline = '';
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 初始化
onMounted(() => {
  getWorkshopList();
  getProductionLineList();
});
</script>

<style scoped>
.chanxian-container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.column-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-icon {
  cursor: pointer;
  font-size: 14px;
  color: #909399;
}

.column-search {
  margin-top: 5px;
}
</style>
